import React, { Component } from 'react'
import { Card, Breadcrumb, Form, Space, Button, Input, Radio, Upload, Modal, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom'
import Channel from 'components/Channel.js'
import styles from './index.module.scss'
// 引入富文本编辑器以及样式
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { baseURL } from 'utils/request'
import { getArticleDetails, publishArticle, updateArticle } from 'api/articles'


export default class ArticlePublish extends Component {
  state = {
    type: 1, // 封面的默认类型
    fileList: [], // 上传的图片存放位置
    previewOpen: false, // 控制图片预览
    previewImage: '', // 预览的图片的地址
    id: this.props.match.params.id // 判断是显示发布文章还是修改文章
  }
  formRef = React.createRef()
  render() {
    // console.log(this.props);
    return (
      <div className={styles.root}>
        <Card title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to='/home'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{this.state.id ? '编辑文章' : '发布文章'}</Breadcrumb.Item>
          </Breadcrumb>
        }>
          <Form ref={this.formRef} labelCol={{ span: 4 }} validateTrigger={['onChange', 'onBlur']} onFinish={this.onFinish} initialValues={{ content: '', type: this.state.type }}>
            <Form.Item name='title' label='标题' rules={[
              { required: true, message: '文章标题不能为空' }
            ]}>
              <Input style={{ width: 300 }} placeholder='请输入文章标题'></Input>
            </Form.Item>

            <Form.Item label='频道' name='channel_id' rules={[
              { required: true, message: '频道不能为空' }
            ]}>
              <Channel></Channel>
            </Form.Item>

            <Form.Item label='封面' name='type'>
              <Radio.Group onChange={this.changeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 4 }}>
              {/* 上传按钮 */}
              {
                this.state.type !== 0 &&
                <Upload
                  fileList={this.state.fileList}
                  listType="picture-card"
                  action={`${baseURL}upload`}
                  name='image'
                  onChange={this.uploadChange}
                  onPreview={this.handlePreview}
                  beforeUpload={this.handleBeforeUpdate}
                >
                  {
                    this.state.fileList.length < this.state.type &&
                    <PlusOutlined></PlusOutlined>
                  }
                </Upload>
              }
              <Modal open={this.state.previewOpen} title={'图片预览'} footer={null} onCancel={this.handleCancel}>
                <img
                  alt="example"
                  style={{
                    width: '100%',
                  }}
                  src={this.state.previewImage}
                />
              </Modal>

            </Form.Item>

            <Form.Item label='内容' name='content' rules={[
              { required: true, message: '文章内容不能为空' }
            ]}>
              <ReactQuill placeholder='请输入文章内容' theme="snow" />
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button type='primary' htmlType='submit'>
                  {this.state.id ? '编辑文章' : '发布文章'}
                </Button>
                <Button onClick={this.addDraft}>存入草稿</Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
  //在刚渲染时就要获取文章详情信息
  async componentDidMount() {
    if (this.state.id) {
      const res = await getArticleDetails(this.state.id)
      // console.log(res);
      const values = {
        ...res.data,
        type: res.data.cover.type
      }
      // 回显数据 用form表单的方法
      this.setState({
        fileList: res.data.cover.images.map(item => {
          return {
            url: item
          }
        }),
        type: res.data.cover.type
      })
      this.formRef.current.setFieldsValue(values)
    }
  }

  // 点击提价发布文章
  onFinish = async (value) => {
    // console.log(value);
    this.save(value, false)
  }
  // 上传文件变化的函数
  uploadChange = ({ fileList }) => {
    // console.log(e);
    this.setState({
      fileList
    })
  }
  // 选择几张图变化的操作
  changeType = (e) => {
    // console.log(e);
    this.setState({
      type: e.target.value,
      fileList: []
    })
  }
  // 图片预览
  handlePreview = (file) => {
    // console.log(file);
    const url = file.url || file.response.data.url
    this.setState({
      previewOpen: true,
      previewImage: url
    })
  }
  // 图片预览按钮的那个叉号
  handleCancel = () => {
    this.setState({
      previewOpen: false,
      previewImage: ''
    })
  }
  // 上传之前对文件作出限制
  handleBeforeUpdate = (file) => {
    // console.log(file);
    if (!['image/jpeg', 'image/png'].includes(file.type)) {
      message.warning('文件格式错误')
      return Upload.LIST_IGNORE
    }
    if (file.size > 1024 * 500) {
      message.warning('文件大小超出限制')
      return Upload.LIST_IGNORE
    }
    return true
  }
  // 存入草稿
  addDraft = async () => {
    const value = await this.formRef.current.validateFields()
    // console.log(value);
    this.save(value, true)
  }
  // 合并发布文章和存入草稿
  save = async (value, draft) => {
    const { type, fileList } = this.state
    if (fileList.length !== type) {
      return message.warning('上传图片数量不正确')
    }
    const images = fileList.map(item => {
      return item.url || item.response.data.url
    })
    if (this.state.id) {
      await updateArticle({
        ...value,
        cover: {
          type,
          images
        },
        id: this.state.id
      },
        draft)
      message.success('修改成功')
    } else {
      await publishArticle({
        ...value,
        cover: {
          type,
          images
        }
      }, draft)
      message.success('发布文章成功')

    }
    this.props.history.push('/home/list')
  }

}
